<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-if="optType != 'view'"
          v-hasPermi="['mes:wm:transfer:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="transferlineList" @selection-change="handleSelectionChange" border>
      <el-table-column label="序号" type="index" width="50"/>
      <el-table-column label="产品物料编码" width="120px" align="center" prop="itemCode" />
      <el-table-column label="产品物料名称" width="150px" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="图号" align="center" prop="drawNumber" />
      <el-table-column label="单价（主）" align="center" prop="price" />
      <el-table-column label="单位（主）" align="center" prop="unitOfMeasure" />
      <el-table-column label="转移数量（主）" align="center" prop="quantityTransfer" width="150">
        <template slot-scope="scope">
          <el-input-number :min="0" :max="99999999999" :disabled="optType =='view'" controls-position="right"
                           size="mini" style="width:100px" v-model="scope.row.quantityTransfer"  @change="handleChangeZhu(scope.$index, scope.row)"

          />
        </template>
      </el-table-column>
      <el-table-column label="单位（辅）" align="center" prop="storageUnit" />
      <el-table-column label="转移数量（辅）" align="center" prop="storageUnitquantity" width="150">
        <template slot-scope="scope">
          <el-input-number :min="0" :max="99999999999" :disabled="optType == 'edit' && scope.row.enableMultiUnit == 'Y'? false:true" controls-position="right"
                           size="mini" style="width:100px"
                           v-model="scope.row.storageUnitquantity"  @change="handleChangeFu(scope.$index, scope.row)" />
        </template>
      </el-table-column>
<!--      转移 从一个库到另个库，库存记录里有批号就有  没有就没有  不需要填写-->
      <el-table-column label="批次号" width="150px" align="center" prop="batchCode">
<!--        <template slot-scope="scope">
          <div style="display: flex; align-items: center; gap: 8px">
            <el-input v-model="scope.row.batchCode" :disabled="scope.row.enableBatchFlag !=='Y'"   />
            <el-switch
                v-if ="scope.row.enableBatchFlag =='Y'"
                v-model="scope.row.autoGenCodeFlag"
                active-color="#13ce66"
                active-text="自动生成"
                @change="handleLineAutoGenCode(scope.row.autoGenCodeFlag,scope.row)"
            >
            </el-switch>
          </div>
        </template>-->
      </el-table-column>
      <el-table-column label="移出仓库" align="center" prop="fromWarehouseName"/>
      <el-table-column label="移出库区" width="120px" align="center" prop="fromLocationName"/>
      <el-table-column label="移出库位" align="center" prop="fromAreaName"/>
      <el-table-column label="移入仓库" align="center" prop="toWarehouseName">
<!--        <template slot-scope="scope">
          <el-select v-model="scope.row.toWarehouseId" placeholder="请选择库区" @change="handleToWarehouseChange($event,scope.row)" >
            <el-option
              v-for="item in toWarehouseList"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId">
            </el-option>
          </el-select>
        </template>-->
      </el-table-column>
      <el-table-column label="移入库区" width="120px" align="center" prop="toLocationName">
<!--        <template slot-scope="scope">
          <el-select v-model="scope.row.toLocationId" placeholder="请选择库区"
                     @change="handleLocationChange($event,scope.row)"
                     @visible-change="handleToLocationVisibleChange(($event,scope.row))"
                     v-loading="locationSelectLoading"
                    >
            <el-option
              v-for="item in locationList"
              :key="item.locationId"
              :label="item.locationName"
              :value="item.locationId">
            </el-option>
          </el-select>
        </template>-->
      </el-table-column>
      <el-table-column label="移入库位" align="center" prop="toAreaName" >
<!--        <template slot-scope="scope">
          <el-select v-model="scope.row.toAreaId" placeholder="请选择库位"
                     @change="handleAreaChange($event,scope.row)"
                     @visible-change="handleVisibleChange(($event,scope.row))"
                     v-loading="areaSelectLoading">
            <el-option
              v-for="item in areaList"
              :key="item.areaId"
              :label="item.areaName"
              :value="item.areaId">
            </el-option>
          </el-select>
        </template>-->
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="clinentName" />
      <el-table-column label="操作" v-if="optType != 'view'" width="120px" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mes:wm:transfer:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
<plan-bom-stock-select ref="planbomselect" v-if="orderCode" :order-code="orderCode" @onSelected="onStockSelected"></plan-bom-stock-select>
  </div>
</template>

<script>
import { listTransferclientline, getTransferclientline, delTransferclientline, addTransferclientline, updateTransferclientline } from "@/api/mes/wm/transferclientline";

import PlanBomStockSelect from "@/components/stockSelect/transferclintmultiunit.vue"
import {getTreeList, getWarehouseList} from "@/api/mes/wm/warehouse"
import {getMdItem} from "@/api/mes/md/mdItem";
import Template from "@/views/print/printtemplate/list.vue";
import {getLocationList} from "@/api/mes/wm/location";
import {getAreaList, getListByWarehouseId} from "@/api/mes/wm/area";
import {genCode} from "@/api/system/autocode/rule";

export default {
  name: "Transferline",
  components: {
    Template,
    PlanBomStockSelect
  },
  props: {
    transferId: null,
    orderCode:null,
    fromWarehouseId: null,
    toWarehouseId: null,
    optType: null,
    toWareLoactionAreaInfo:null
  },
  data() {
    return {
      areaSelectLoading:false,
      locationSelectLoading:false,
      //移入仓库
      toWarehouseList:[],
      //移入库区
      locationList:[],
      //移入库位
      areaList:[],
      fromWarehouse: null,
      warehouseInfo:[],
      warehouseOptions:[],
      warehouseProps:{
        multiple: false,
        value: 'pId',
        label: 'pName',
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 转移单行表格数据
      transferlineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        transferId: this.transferId,
        materialStockId: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantityTransfer: null,
        quantityMax: null,
        workorderId: null,
        workorderCode: null,
        batchCode: null,
        fromWarehouseId: null,
        fromWarehouseCode: null,
        fromWarehouseName: null,
        fromLocationId: null,
        fromLocationCode: null,
        fromLocationName: null,
        fromAreaId: null,
        fromAreaCode: null,
        fromAreaName: null,
        toWarehouseId: null,
        toWarehouseCode: null,
        toWarehouseName: null,
        toLocationId: null,
        toLocationCode: null,
        toLocationName: null,
        toAreaId: null,
        toAreaCode: null,
        toAreaName: null,
        expireDate: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        vendorNick: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        itemCode: [
          { required: true, message: "请选择移出的物资", trigger: "blur" }
        ],
        toWarehouseId: [
          { required: true, message: "请指定移入仓库", trigger: "blur" }
        ],
        quantityTransfer: [
          { required: true, message: "转移数量不能为空", trigger: "blur" }
        ],

      }
    };
  },
  created() {
    this.getList();
    this.getWarehouseList();
    this.getWarehouse()
  },
  methods: {
    /** 查询转移单行列表 */
    getList() {
      this.loading = true;
      listTransferclientline(this.queryParams).then(response => {
        this.transferlineList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    handleChangeZhu(index,row){
      if('Y' == row.enableMultiUnit) {
        console.log("fixedddddddddd")
        if (row.storageUnitType === 'fixed') {
          console.log(row)
          // 库存单位数量=主数量 / 换算比例
          row.storageUnitquantity = parseFloat(
            (row.quantityTransfer / row.storageRatio).toFixed(7)
          );
          console.log("ddddddd",row.storageUnitquantity)
        }
        //浮动换算就得 填写两个数量计算出浮动率就可以了
        if (row.storageUnitType === 'float') {
          if (row.storageUnitquantity > 0 && row.quantityTransfer > 0) {

            // 计算新换算比例 = 主数量 / 库存单位数量
            row.storageRatio = parseFloat(
              (row.quantityTransfer / row.storageUnitquantity).toFixed(4)
            );
          }
        }
        if (row.storageUnitquantity > row.quantityMax) {
          this.$modal.msgError("当前转移数量（主）大于库存数量，请修改，否则将无法出库");
          return
        }
      }
    },
    handleChangeFu(index,row){
      if (row.storageUnitType === 'fixed') {
        console.log("fuuuuuuuuuuuuuu")
        console.log("fuuuuuuuuuuuuuu",row)
        // 主数量 = 库存单位数量 * 换算比例
        row.quantityTransfer = parseFloat(
          (row.storageUnitquantity * row.storageRatio).toFixed(7)
        );
      }

      //浮动换算就得 填写两个数量计算出浮动率就可以了
      if (row.storageUnitType === 'float') {
        if (row.storageUnitquantity > 0 && row.quantityTransfer > 0) {

          // 计算新换算比例 = 主数量 / 库存单位数量
          row.storageRatio = parseFloat(
            (row.quantityTransfer / row.storageUnitquantity).toFixed(4)
          );
        }
      }
      if(row.quantityTransfer > row.quantityMax){
        this.$modal.msgError("当前转移数量（主）大于库存数量，请修改，否则将无法出库");
        return
      }
    },
    getWarehouseList(){
      var toWarehouseId=this.toWarehouseId
      getTreeList().then(response => {
        // 这个是过滤移入仓库的 ，现在不用了
    /*    var filteredEntities = response.data.filter(function(entity) {
          return entity.warehouseId == toWarehouseId;
        });
        console.log("filteredEntities",filteredEntities)
        this.warehouseOptions = filteredEntities;*/
        if (response.data) {
          this.warehouseOptions = response.data.filter((el) => {
            return el.warehouseCode.indexOf('VIR') == -1;
          });
        }
        this.warehouseOptions.map(w =>{
          w.children.map(l =>{
            let lstr = JSON.stringify(l.children).replace(/locationId/g, 'lId').replace(/areaId/g, 'pId').replace(/areaName/g, 'pName');
                  l.children = JSON.parse(lstr);
          });

          let wstr = JSON.stringify(w.children).replace(/warehouseId/g, 'wId').replace(/locationId/g, 'pId').replace(/locationName/g, 'pName');
          w.children = JSON.parse(wstr);

        });
        let ostr=JSON.stringify(this.warehouseOptions).replace(/warehouseId/g,'pId').replace(/warehouseName/g, 'pName');
        this.warehouseOptions = JSON.parse(ostr);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        lineId: null,
        transferId: this.transferId,
        materialStockId: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantityTransfer: null,
        workorderId: null,
        workorderCode: null,
        batchCode: null,
        fromWarehouseId: this.fromWarehouseId,
        fromWarehouseCode: null,
        fromWarehouseName: null,
        fromLocationId: null,
        fromLocationCode: null,
        fromLocationName: null,
        fromAreaId: null,
        fromAreaCode: null,
        fromAreaName: null,
        toWarehouseId: null,
        toWarehouseCode: null,
        toWarehouseName: null,
        toLocationId: null,
        toLocationCode: null,
        toLocationName: null,
        toAreaId: null,
        toAreaCode: null,
        toAreaName: null,
        expireDate: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        vendorNick: null,
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
        ,storageUnitType:null,
        storageUnit:null,
        storageRatio:0,
        storageUnitquantity:0,
        enableMultiUnit:'N',
        price:null,
        //不保存到后台用于转移数量比大小 不能超库存数量
        quantityMax:null,
      };
      this.fromWarehouse = null;
      this.warehouseInfo = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.lineId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
   /*   this.reset();
      this.open = true;
      this.title = "添加转移单行";*/
      this.$refs.planbomselect.showFlag = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const lineId = row.lineId || this.ids

        getTransferline(lineId).then(response => {
          this.form = response.data;
          this.fromWarehouse = response.data.fromWarehouseName+" / "+response.data.fromLocationName+" / "+response.data.fromAreaName;
        /*  this.warehouseInfo[0] = response.data.toWarehouseId;
          this.warehouseInfo[1] = response.data.toLocationId;
          this.warehouseInfo[2] = response.data.toAreaId;*/
          let aa=[response.data.toWarehouseId,response.data.toLocationId,response.data.toAreaId]
          this.warehouseInfo=aa
          this.open = true;
          this.title = "修改转移单行";
          console.log("upupppp",this.warehouseInfo)
          console.log("upuppppOptions",this.warehouseOptions)
          this.$forceUpdate()
        });


    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.quantityTransfer <= 0){
            this.$modal.msgError("转移数量（主）必须大于0");
            return
          }
          if(this.form.quantityTransfer > this.form.quantityMax){
            this.$modal.msgError("当前转移数量（主）大于库存数量，请修改，否则将无法出库");
            return
          }
          if(this.form.enableMultiUnit =='Y'){
            if(this.form.storageUnitquantity <= 0){
              this.$modal.msgError("转移数量（辅）必须大于0");
              return
            }
          }
          if (this.form.lineId != null) {
            updateTransferline(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTransferline(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    async handleLineAutoGenCode(autoGenCodeFlag, row) {
      try {
        if (autoGenCodeFlag) {
          const codedata = await genCode('BATCH_CODE_NEW')
          this.$set(row, 'batchCode', codedata)
        } else {
          this.$set(row, 'batchCode', null)
        }
        // 自动同步开关状态（根据业务需要）
        this.$set(row, 'autoGenCodeFlag', autoGenCodeFlag)
      } catch (error) {
        console.error('生成批次号失败:', error)
        this.$set(row, 'autoGenCodeFlag', !autoGenCodeFlag) // 回滚开关状态
      }
      /*   this.$nextTick(() => {
           this.tableKey++
         })*/
    },
    /** 删除按钮操作 */
    handleDelete(row) {
    /*  const lineIds = row.lineId || this.ids;
      this.$modal.confirm('是否确认删除转移单行编号为"' + lineIds + '"的数据项？').then(function() {
        return delTransferline(lineIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});*/
      // 这里用库存的id  因为库存的id肯定不能重复  比如以前有2条 现在加一条 不管是新加的还是以前的库存id都有且唯一
      const index = this.transferlineList.findIndex(item => item.materialStockId === row.materialStockId);
      if (index !== -1) {
        this.transferlineList.splice(index, 1);
        // this.$message.success("删除成功");
      }
    },
    /**
     * 将选择物料合并到transferlineList
     * 如果transferlineList中已存在相同materialStockId，则保留transferlineList的记录不动
     */
    //物料选择弹出框
    onStockSelected(objList){
      console.log("sssssssss",objList)
        // 创建materialStockId的映射，用于快速查找transferlineList中已存在的记录
        const collectionBMap = new Map();
      if(this.transferlineList.length >0){
        this.transferlineList.forEach(item => {
          if (item.materialStockId) {
            collectionBMap.set(item.materialStockId, item);
          }
        });
      }
        // 遍历所选物料库存，处理每条记录
         objList.forEach(itemStock => {
           // 如果objList中的记录没有materialStockId，跳过  应该不会出现
            if (!itemStock.materialStockId) {
              return;
            }
          // 检查transferlineList中是否已存在相同materialStockId
          if (!collectionBMap.has(itemStock.materialStockId)) {
            // 如果不存在，创建新记录并添加字段映射
            const newItem = {
              transferId: this.transferId,
              materialStockId: itemStock.materialStockId,
              itemId: itemStock.itemId,
              itemCode: itemStock.itemCode,
              itemName: itemStock.itemName,
              specification: itemStock.specification,
              unitOfMeasure: itemStock.unitOfMeasure,
              quantityTransfer: itemStock.quantityOnhand,
              quantityMax:itemStock.quantityOnhand,
              workorderId: itemStock.workorderId,
              workorderCode: itemStock.workorderCode,
              batchCode: itemStock.batchCode,

              fromWarehouseId: itemStock.warehouseId,
              fromWarehouseCode: itemStock.warehouseCode,
              fromWarehouseName: itemStock.warehouseName,
              fromLocationId: itemStock.locationId,
              fromLocationCode: itemStock.locationCode,
              fromLocationName: itemStock.locationName,
              fromAreaId: itemStock.areaId,
              fromAreaCode: itemStock.areaCode,
              fromAreaName: itemStock.areaName,
              //移入仓库信息从单据头带过的的
              toWarehouseId: this.toWareLoactionAreaInfo.toWarehouseId,
              toWarehouseCode: this.toWareLoactionAreaInfo.toWarehouseCode,
              toWarehouseName: this.toWareLoactionAreaInfo.toWarehouseName,
              toLocationId: this.toWareLoactionAreaInfo.toLocationId,
              toLocationCode: this.toWareLoactionAreaInfo.toLocationCode,
              toLocationName: this.toWareLoactionAreaInfo.toLocationName,
              toAreaId: this.toWareLoactionAreaInfo.toAreaId,
              toAreaCode: this.toWareLoactionAreaInfo.toAreaCode,
              toAreaName: this.toWareLoactionAreaInfo.toAreaName,

              price:itemStock.price,
              expireDatel: itemStock.expireDatel,
              vendorId: itemStock.vendorId,
              vendorCode: itemStock.vendorCode,
              vendorName: itemStock.vendorName,
              vendorNick: itemStock.vendorNick,

              enableMultiUnit: itemStock.enableMultiUnit,
              storageUnit: itemStock.storageUnit,
              storageUnitType: itemStock.storageUnitType,
              storageRatio: itemStock.storageRatio,
              enableBatchFlag:itemStock.enableBatchFlag,
              storageUnitquantity:itemStock.storageUnitquantity,
              //启用的批次号 可以填写   默认false
              autoGenCodeFlag:false
            };
            // 添加到transferlineList
            this.transferlineList.push(newItem);
            collectionBMap.set(itemStock.materialStockId, newItem);
            console.log("xuanzezzzzz",this.transferlineList)
          }
          // 如果已存在相同materialStockId，保留transferlineList的记录不做处理
        });

        return this.transferlineList;
    },
    //选择默认的仓库、库区、库位
    handleToWarehouseChanged(obj) {
      if(obj !=null){
        this.form.toWarehouseId = obj[0];
        this.form.toLocationId = obj[1];
        this.form.toAreaId = obj[2];
      }
    },
   /*   这里是移入仓库可以手动填写的   不用了 */
    //获取仓库
    getWarehouse(){
      this.toWarehouseList=[]
      getWarehouseList().then(response => {
        this.toWarehouseList = response.data.filter((el) =>{
          return el.warehouseCode.indexOf('VIR') == -1;
        })
      });
      this.getLocation()
      this.getArea()
    },
    //选择仓库
    handleToWarehouseChange(value,row){
      console.log("cccccccc",value)
      //清空库区 库位
      if(row.toLocationId){
        this.$set(row, 'toLocationId', null)
        this.$set(row, 'toLocationName', null)
        this.$set(row, 'toLocationCode', null)
      }
      if(row.toAreaId){
        this.$set(row, 'toAreaId', null)
        this.$set(row, 'toAreaName', null)
        this.$set(row, 'toAreaCode', null)
      }
      row.toWarehouseCode=this.toWarehouseList.filter(item => item.warehouseId === value)[0].warehouseCode
      row.toWarehouseName=this.toWarehouseList.filter(item => item.warehouseId === value)[0].warehouseName
    },
    //选择库区
    handleLocationChange(value,row){
      //清空库位
      if(row.areaId){
        this.$set(row, 'areaId', null)
        this.$set(row, 'areaName', null)
        this.$set(row, 'areaCode', null)
      }

      row.toLocationName=this.locationList.filter(item => item.locationId === value)[0].locationName
      row.toLocationCode=this.locationList.filter(item => item.locationId === value)[0].locationCode
      this.$forceUpdate()
      // this.tableKey++;
    },
    //获取库区
    getLocation(warehouseId){
      this.locationList=[]
      if(warehouseId){
        getLocationList({warehouseId:warehouseId}).then(response => {
          this.locationList = response.data;
        });
      }else{
        getLocationList().then(response => {
          this.locationList = response.data;
        });
      }
    },
    //获取库位
    getArea(locationId){
      this.areaList=[]
      if(locationId){
        getAreaList({locationId:locationId}).then(response => {
          this.areaList = response.data;
        });
      }else{
        getAreaList().then(response => {
          this.areaList = response.data;
        });
      }
    },
    //下拉的时候加载仓库下的库区
    handleToLocationVisibleChange(value,row){
      this.locationSelectLoading=true
      if (value) {
        //加载仓库下的库区
        this.getLocation(value.toWarehouseId)
        this.locationSelectLoading=false
        // 在这里执行打开下拉框时的操作
      } else {
        console.log('下拉框关闭了');
        // 在这里执行关闭下拉框时的操作
      }
    },
    //下拉的时候加载库区下的库位
    handleVisibleChange(value,row){
      this.areaSelectLoading=true
      if (value) {
        this.getArea(value.locationId)
        this.areaSelectLoading=false
        console.log("qqqqqqqqqq",value)
        // 在这里执行打开下拉框时的操作
      } else {
        console.log('下拉框关闭了');
        // 在这里执行关闭下拉框时的操作
      }

    },
    //选择库位
    handleAreaChange(value,row){
      console.log("11111111111111",row)
      this.$set(row, 'toAreaName', this.areaList.filter(item => item.areaId === value)[0].areaName)
      this.$set(row, 'toAreaCode', this.areaList.filter(item => item.areaId === value)[0].areaCode)
      this.$forceUpdate()
    },
  }
};
</script>
